/**
 * 楼盘动态
 */
define(function(require, exports, module) {
    var $ = require("jquery");
    var util = require("util");
    var ui = require("ui");
    var tmpl = require("tmpl");
    var datepicker = require("datepicker");
    var dialog = require("dialog");

    require("select");
    require("pagination");
    var buidingSetting = require("./building_setting");
    var api_prefix = G_CONFIG["api_prefix"] + "/qmyx/building-info/"; //api前缀

    var BuildingHouseType = {
        list:[],
        labels:[], //楼盘动态标签
        pagerInited:false,
        pageIndex:1,
        pageSize:10,
        init: function() {
            this.pageIndex = 1;
            this.bindEvent();
            if(buidingSetting.building_id){
                this.getList();
            }
        },
        initPager:function(total){
            var _this = this;
            $('#housetype_pager').pagination(total,{
                num_edge_entries: 1, //边缘页数
                num_display_entries: 4, //主体页数
                callback: function (pageIndex, jq) {
                    _this.pageIndex = pageIndex;
                    _this.getList(pageIndex);
                },
                items_per_page: this.pageSize //每页显示1项
            });
            this.pagerInited = true;
        },
        bindEvent: function() {
            var _this = this;
            $("#btn_add").off().on("click",function(e){
                e.preventDefault();
                _this.showAddHouseType("",{});
            });
            $("#housetype_grid").on("click", ".js-edit", function(e) {
                e.preventDefault();
                var oid = $(e.currentTarget).closest("td").attr("id") || "";
                if (oid) {
                    _this.showUpdateHouseType(oid);
                }
            });
            $("#housetype_grid").on("click", ".js-del", function(e) {
                e.preventDefault();
                var oid = $(e.currentTarget).closest("td").attr("id") || "";
                if (oid) {
                    _this.del(oid);
                }
            });
            $("#housetype_grid").on("mouseenter","tr",function(){
                $(this).find(".js-oper-btn").show();
            });
            $("#housetype_grid").on("mouseleave","tr",function(){
                $(this).find(".js-oper-btn").hide();
            });
        },
        showUpdateHouseType: function(oid) {
            var house_type;
            $.each(this.list, function(i, item) {
                if (item.b_regbroker_house_typeId == oid) {
                    house_type = item;
                    return false;
                }
            });
            if (!house_type) {
                ui.showErrTip("未找到对象");
                return;
            }
            this.showAddHouseType(house_type.b_regbroker_house_typeId, house_type);
        },
        //新增,编辑户型弹层
        showAddHouseType: function(oid, house_type) {
            if(!buidingSetting.proj_id){
                ui.showErrTip("请先选择项目");
                return;
            }
            if(!buidingSetting.building_id){
                ui.showErrTip("请先添加项目楼盘");
                return;
            }
            var title = oid ? "编辑记录" : "新增记录";
            var html = tmpl("add_housetype_tmpl", house_type);
            var _this = this;
            var d = dialog({
                id:"save_housetype_dialog",
                title: title,
                content: html,
                width:750,
                height:510,
                onshow: function(){
                    $("#house_type_name").focus();
                    ui.initCount("buildingArea");
                    ui.initCount("displayOrder");
                    require.async(["uploader"], function() {
                        $('#fileupload').fileupload({
                            dataType: 'json',
                            url: G_CONFIG["api_prefix"] + "common/file/upload-image",
                            add:function(e,data){
//                                if($("#td_house_type_pic").find("img").length >= 5){
//                                    ui.showErrTip("最多只能上传五张图片");
//                                    return false;
//                                }
                                if(util.checkIsImagFile(data.files[0])){
                                    data.submit();
                                    $("#img_wrap").append('<div class="upload-process">上传中...</div>');
                                }else{
                                    $("#house_type_pic_err").html("请选择图片文件(jpg|jpeg|png)").show();
                                }
                            },
                            done: function(e, data) {
                                $("#img_wrap").find(".upload-process").remove();
                                var res = data.result;
                                if (res.retCode == "0") { //上传成功
                                    var img_url = res.data.path;
                                    var str =  '<div class="fl pic-item"><span class="pic-del" title="删除"><i class="icon-op icon-op-del"></i></span><img src="' + img_url + '" alt="户型图片" /></div>';
                                    $("#fileupload").before(str);
                                    $("#house_type_pic_err").html("").hide();
                                } else {
                                    $("#house_type_pic_err").html("上传失败:" + res.errMsg).show();
                                }
                            }
                        });
                    });
                    //初始化编辑器
                    UM.delEditor('editor');
                    var editor = UM.createEditor('editor');
                    editor.ready(function(){
                        if(house_type.Introduction){
                            editor.setContent(house_type.Introduction);
                        }
                    });
                    $("#td_house_type_pic").on("click",".pic-del",function(e){
                        util.confirm("您确定要删除吗?",{ok:function(){
                            $(e.currentTarget).parent().remove();
                        }});
                    });
                },
                ok: function() {
                    var house_type_name = ui.checkField("house_type_name", true);
                    var house_type_code = ui.checkField("house_type_code", true);
                    var bldarea = ui.checkNumber("bldarea", true,"建筑面积应为正数",/^\d+(\.\d{1,2})?$/);
                    var orders = ui.checkNumber("orders", true,"显示顺序应为正整数",/^\d+$/);
                    var introduction = ui.checkEditor("editor",false);
                    var house_type_pic = _this.checkHouseTypePic();
                    
                    if (house_type_name === false || house_type_code === false 
                            || bldarea === false || orders === false || house_type_pic === false) {
                        return false;
                    }
                    _this.save(oid,house_type_name,house_type_code,bldarea,orders,introduction,house_type_pic);
                    return false;
                },
                cancel: function() {
                }
            });
            d.showModal();
        },
        checkHouseTypePic:function(){
            var $img = $("#td_house_type_pic").find("img");
            if($img.length == 0){
                $("#house_type_pic_err").html("户型图片不能为空").show();
                return false;
            }
            $("#house_type_pic_err").html("").hide();
            var imgArr = [];
            $img.each(function(){
                imgArr.push($(this).attr("src"));
            });
            return imgArr;
        },
        //获取户型列表
        getList:function(pageIndex){
            if(typeof pageIndex == "undefined"){
                pageIndex = 1;
                this.pagerInited = false;
            }
            var url = api_prefix + "get-house-type-list";
            var data = {
                regbroker_lpinfo_id:buidingSetting.building_id,
                pageIndex:pageIndex,
                pageSize:this.pageSize
            };
            util.myAjax({
                url: url,
                type: "GET",
                cache: false,
                data: data,
                context: this,
                success: function(json) {
                    if (json.retCode == 0) {
                        this.list = json.data.list || []; //列表
                        this.initTable(this.list);
                        if(!this.pagerInited){
                            this.initPager(json.data.total);
                        }
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                },
                complete:function(){
                    ui.removeLoading();
                }
            });
            ui.loading();
        },
        initTable:function(list){
            var html = tmpl('housetype_row_tmpl', {list: list});
            $("#housetype_grid").html(html);
        },
        del:function(oid){
            var _this = this;
            util.confirm("您确定要删除吗？", {
                ok: function() {
                    var url = api_prefix + "del-house-type";
                    var data = {
                        b_regbroker_house_typeId: oid
                    };
                    util.myAjax({
                        url: url,
                        type: "POST",
                        context: _this,
                        data: data,
                        success: function(json) {
                            if (json.retCode == 0) {
                                _this.getList();
                            } else {
                                ui.showErrTip(json.errMsg);
                            }
                        }
                    });
                }
            });
        },
        //添加、编辑合作户型
        save: function(oid,house_type_name,house_type_code,bldarea,orders,introduction,house_type_pic) {
            if(this.isSubmit){
                ui.showErrTip("请勿重复提交");
                return;
            }
            var url = api_prefix + "write-house-type";
            var data = {
                house_type_name: house_type_name,
                house_type_code: house_type_code,
                bldarea: bldarea,
                orders: orders,
                Introduction: introduction,
                house_type_pic:house_type_pic,
                regbroker_lpinfo_id:buidingSetting.building_id
            };
            if(oid){ //更新
                data.b_regbroker_house_typeId = oid;
            }
            util.myAjax({
                url: url,
                type: "POST",
                context: this,
                data: data,
                success: function(json) {
                    this.isSubmit = false;
                    if (json.retCode == 0) {
                        dialog.get("save_housetype_dialog").remove();
                        ui.showSucTip("操作成功");
                        this.getList();
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                },
                complete:function(){
                    this.isSubmit = false;
                }
            });
            this.isSubmit = true;
        }
    };
    module.exports = BuildingHouseType;
});